package com.mhr.ai.cr.provider.impl

import com.mhr.ai.cr.provider.AIModel
import com.mhr.ai.cr.provider.AIProvider
import com.mhr.ai.cr.provider.AIProviderConfig
import org.springframework.ai.chat.messages.UserMessage
import org.springframework.ai.chat.prompt.Prompt
import org.springframework.ai.deepseek.DeepSeekChatModel
import org.springframework.ai.deepseek.DeepSeekChatOptions
import org.springframework.ai.deepseek.api.DeepSeekApi

/**
 * DeepSeek 提供商实现
 * 使用 Spring AI DeepSeek 进行代码审核
 */
class DeepSeekProvider : AIProvider {
    
    override val providerName: String = "DeepSeek"
    
    override fun getSupportedModels(): List<AIModel> {
        return listOf(
            AIModel(
                id = "deepseek-chat",
                displayName = "DeepSeek Chat",
                description = "DeepSeek 通用对话模型",
                maxTokens = 32000
            ),
            AIModel(
                id = "deepseek-coder",
                displayName = "DeepSeek Coder",
                description = "专门针对代码优化的模型",
                maxTokens = 16000
            )
        )
    }
    
    override fun isConfigValid(config: AIProviderConfig): Boolean {
        return config.apiKey.isNotBlank() && 
               config.model.isNotBlank() &&
               getSupportedModels().any { it.id == config.model }
    }
    
    override fun reviewCode(prompt: String, config: AIProviderConfig): String {
        try {
            // 创建 DeepSeek API 实例
            val deepSeekApi = DeepSeekApi.builder()
                .apiKey(config.apiKey)
                .apply {
                    config.baseUrl?.let { baseUrl(it) }
                }
                .build()
            
            // 创建聊天选项
            val options = DeepSeekChatOptions.builder()
                .model(config.model)
                .temperature(config.temperature.toDouble())
                .maxTokens(config.maxTokens)
                .build()
            
            // 创建聊天模型
            val chatModel = DeepSeekChatModel.builder()
                .deepSeekApi(deepSeekApi)
                .defaultOptions(options)
                .build()
            
            // 构建请求
            val userMessage = UserMessage(prompt)
            val chatPrompt = Prompt(listOf(userMessage))
            
            // 调用 API
            val response = chatModel.call(chatPrompt)
            
            return response.result?.output?.text 
                ?: throw IllegalStateException("DeepSeek响应为空")
        } catch (e: Exception) {
            throw RuntimeException("DeepSeek API调用失败: ${e.message}", e)
        }
    }
    
    override fun testConnection(config: AIProviderConfig): Boolean {
        return try {
            reviewCode("测试连接", config)
            true
        } catch (e: Exception) {
            false
        }
    }
}